<template>
    <div class="audio-table-nav">
        <n-input style="width: 280px;margin-right: 10px;" v-model:value="userSearchValue" @keydown.enter="seatchAudio" placeholder="请输入搜索关键字（歌名、歌手、作词）" />
        <n-button style="margin-right: 10px;" type="primary" @click="seatchAudio">搜索</n-button>
        <n-button type="error" @click="delteAudio">删除</n-button>
    </div>

    <n-data-table remote bordered :single-line="false" ref="userTable" :row-key="userRowKey" :columns="userColumns" :data="userData" :loading="userLoading" :pagination="userPagination" @update:page="handleAudioPageChange"
        @update:checked-row-keys="handleCheck" />
</template>
    
<script setup lang='ts'>

import { DataTableColumns, NInput, NButton, NSwitch, NSelect, NDatePicker, DataTableRowKey, useMessage } from 'naive-ui';
import { ref, reactive, onMounted, h, Component, onBeforeMount } from 'vue'
import { searchAudio, deleteAudio, updateUserInfo, getAllUser } from '../../../ajax'
import { useSystemConfigStore, userInfoStore } from '../../../store';
import { bytesToSize, formatLevel } from '../../../util/calculate'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router';

onBeforeMount(() => {
    if (userInfo.roles == 'user') {
        useSystemConfig.changeSetPage('systemConfig')
        router.replace({ name: 'systemConfig' })
        message.warning('没有权限用户禁止使用此功能，已跳转至系统配置')
    }
})

onMounted(async () => {
    // 获取音频列表数据
    await updateUserData()
})


const userInfo = userInfoStore()
const useSystemConfig = useSystemConfigStore()
const router = useRouter()
const message = useMessage()


// 音乐表的数据类型
type UserRowData = {
    _id: string,
    joinDate: number,
    loginDate: number,
    username: string,
    level: number,
    disable: number,
    cloundSize: number,
    useCloundSize: number,
    cloundAuth: boolean,
    loginIp: Array<LoginIP>,
    client: Array<Client>,
    roles: string,
    available: boolean,
    operator: Array<string>
}
type LoginIP = {
    previousIp: string,
    currentIp: string
}
type Client = {
    previousClient: string
    currentClient: string
}
type Select = {
    label: string,
    value: string,
    disable?: boolean
}


// 账户权限的枚举
const selectRolesOptions: Select[] = [
    {
        label: '用户',
        value: 'user'
    },
    {
        label: '管理',
        value: 'admin'
    },
    {
        label: '超级管理',
        value: 'root'
    }
]


// 每一行数据都要有唯一的 key
const userRowKey = (row: UserRowData) => row._id
// 获取数据的中数组中的index
const getAudioDataIndex = (_id: string) => {
    return userData.findIndex((item: { _id: string; }) => item._id === _id)
}
// 是否展示原数据或者编辑栏
// const ShowOrEdit: Component = defineComponent({
//     props: {
//         value: [String, Number, Boolean],
//         onUpdateValue: [Function]
//     },
//     setup(props) {

//         const isEdit = ref(false)
//         const inputRef = ref()
//         const inputValue = ref(props.value)

//         function handleOnClick() {
//             isEdit.value = true
//             nextTick(() => {
//                 inputRef.value.focus()
//             })
//         }

//         function handleChange() {
//             props.onUpdateValue!(inputValue.value)
//             isEdit.value = false
//         }

//         return () => h(
//             'div',
//             {
//                 onClick: handleOnClick
//             },
//             isEdit.value
//                 ? h(NInput as Component, {
//                     ref: inputRef,
//                     value: inputValue.value,
//                     onUpdateValue: (v: string | number | boolean | undefined) => {
//                         inputValue.value = v
//                     },
//                     onChange: handleChange,
//                 })
//                 : props.value
//         )
//     }
// })


// 歌曲表是否加载
const userLoading = ref(true)
// 歌曲表ref
const userTable = ref()
// 表单要搜索的值
const userSearchValue = ref()
// 歌曲表checked数据
const userCheckedRowKeys = ref<DataTableRowKey[]>([])
// 歌曲表数据
const userData = reactive<UserRowData[]>([])
// 歌曲表配置
const userColumns: DataTableColumns<UserRowData> = [
    { // selection
        type: 'selection',
    },
    { // 展开高级选项
        type: 'expand',
        title: '高级',
        align: 'center',
        width: 50,
        expandable: () => true,
        renderExpand: (rowData) => {
            return h('div', { style: 'display:flex;justify-content: space-around;' },
                [
                    h('div', { style: '' }, [
                        h('div', `上次登陆IP：${rowData.loginIp[0].previousIp}`),
                        h('div', `本次登陆IP：${rowData.loginIp[0].currentIp}`)

                    ]),

                    h('div', { style: '' }, [
                        h('div', `上次登陆地址/设备：${rowData.client[0].previousClient}`),
                        h('div', `本次登陆地址/设备：${rowData.client[0].previousClient}`)
                    ]),

                    userInfo.roles == 'root'
                        ? h('div', { style: 'display:flex;align-items: center;' }, [
                            h('div', '变更权限：'),
                            h(NSelect, {
                                style: 'width:120px',
                                value: rowData.roles,
                                placeholder: "请选择权限",
                                options: selectRolesOptions,
                                onUpdateValue: async (value: string) => {
                                    const result = await updateUserInfo(rowData._id, 'roles', value)
                                    if (result.data.code == 0) {
                                        rowData.roles = value
                                        message.success(result.data.message)
                                    } else {
                                        message.error(result.data.message)
                                    }
                                }
                            })
                        ])
                        : ''
                ]
            )
        }
    },
    { // 加入时间
        key: 'joinDate',
        title: '加入时间',
        align: 'center',
        width: 80,
        render(row) {
            return `${dayjs(row.joinDate as number).format('YYYY-MM-DD HH:mm:ss')}`
        },
    },
    { // 最近登陆时间
        key: 'loginDate',
        title: '登陆时间',
        align: 'center',
        width: 80,
        render(row) {
            return `${dayjs(row.loginDate as number).format('YYYY-MM-DD HH:mm:ss')}`
        },
    },
    { // 用户名
        key: 'username',
        title: '用户名',
        align: 'center',
        width: 140,
    },
    { // 等级
        key: 'level',
        title: '等级',
        align: 'center',
        width: 50,
        render(row) {
            return `${formatLevel(row.level)}`
        }
    },
    { // 封号时长
        key: 'disable',
        title: '封号时长',
        align: 'center',
        width: 100,
        render(row) {
            const index = getAudioDataIndex(row._id)
            return h(NDatePicker, {
                value: row.disable <= Date.now() ? null : row.disable,
                type:"datetime",
                clearable: true,
                onUpdateValue: async (v: number) => {
                    // 更新数据库
                    const result = await updateUserInfo(row._id, 'disable', v)
                    if (result.data.code == 0) {
                        userData[index].disable = v
                        message.success(result.data.message)
                    } else {
                        message.error(result.data.message)
                    }
                }
            })
        }
    },
    { // 云空间
        key: 'cloundSize',
        title: '云空间',
        align: 'center',
        width: 100,
        render(row) {
            return `${bytesToSize(row.useCloundSize)} / ${bytesToSize(row.cloundSize)}`
        },
    },
    { // 云空间状态
        key: 'cloundAuth',
        title: '云空间状态',
        align: 'center',
        width: 80,
        render(row) {
            const index = getAudioDataIndex(row._id)
            return h(NSwitch as Component, {
                value: row.cloundAuth,
                onUpdateValue: async (v: boolean) => {
                    // 更新数据库
                    const result = await updateUserInfo(row._id, 'cloundAuth', v)
                    if (result.data.code == 0) {
                        userData[index].cloundAuth = v
                        message.success(result.data.message)
                    } else {
                        message.error(result.data.message)
                    }
                }
            })
        }
    },
    { // 可登录
        key: 'available',
        title: '可登录',
        align: 'center',
        width: 80,
        render(row) {
            const index = getAudioDataIndex(row._id)
            return h(NSwitch as Component, {
                value: row.available,
                onUpdateValue: async (v: boolean) => {
                    // 更新数据库
                    const result = await updateUserInfo(row._id, 'available', v)
                    if (result.data.code == 0) {
                        userData[index].available = v
                        message.success(result.data.message)
                    } else {
                        message.error(result.data.message)
                    }
                }
            })
        }
    }
]
// 歌曲表页尾
const userPagination = reactive({
    page: 1,
    itemCount: 0,
    pageSize: 4,
    prefix({ itemCount }) {
        return `你选中了 ${userCheckedRowKeys.value.length} 行。乐库共：${itemCount} 条数据。`
    }
})


// 选中歌曲表一行
const handleCheck = (rowKeys: DataTableRowKey[]) => {
    userCheckedRowKeys.value = rowKeys
}
// 搜索乐库
const seatchAudio = async () => {
    userPagination.page = 1
    await updateUserData()
}
// 切换歌曲表页码
const handleAudioPageChange = async (page: number) => {
    userPagination.page = page
    await updateUserData()
}
// 删除音频
const delteAudio = async () => {
    if (userCheckedRowKeys.value.length !== 0) {
        for (let index = 0; index < userCheckedRowKeys.value.length; index++) {
            const element = userCheckedRowKeys.value[index];
            await deleteAudio(element as string)
        }
        await updateUserData()
    } else {
        message.warning('未选中数据')
    }
}


// 更新音频数据的方法
const updateUserData = async () => {
    // 加载audio数据并清空原数据
    userLoading.value = true
    userData.length = 0
    userPagination.itemCount = 0
    userCheckedRowKeys.value.length = 0

    if (userSearchValue.value) {

        const result = await searchAudio(userSearchValue.value, userPagination.page, userPagination.pageSize)
        if (result.data.code == 0) {
            // 加载表格数据
            result.data.data.map((v: any) => userData.push(v))
            // 更新库中总数据
            userPagination.itemCount = result.data.count
            // 取消加载状态
            userLoading.value = false
        } else {
            // 取消加载状态
            userLoading.value = false
            message.error(result.data.message)
        }

    } else {

        const result = await getAllUser(userPagination.page, userPagination.pageSize)
        if (result.data.code == 0) {
            // 加载表格数据
            result.data.data.map((v: any) => userData.push(v))
            // 更新库中总数据
            userPagination.itemCount = result.data.count
            // 取消加载状态
            userLoading.value = false
        } else {
            // 取消加载状态
            userLoading.value = false
            message.error(result.data.message)
        }

    }

}

</script>
    
<style scoped lang="less">
.audio-table-nav {
    width: 100%;
    display: flex;
    margin-bottom: 8px;

}
</style>